package com.pxmeta.app.controller.user;


import cn.dev33.satoken.annotation.SaCheckLogin;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.google.common.collect.Maps;
import com.pxmeta.common.constant.Status;
import com.pxmeta.common.core.domain.AjaxResult;
import com.pxmeta.common.utils.SecurityUtils;
import com.pxmeta.user.entity.*;
import com.pxmeta.user.entity.dto.ApplyWithdrawDTO;
import com.pxmeta.user.entity.vo.SubordinateUserVO;
import com.pxmeta.user.entity.vo.UserBillVO;
import com.pxmeta.user.service.IUserBillService;
import com.pxmeta.user.service.IUserService;
import com.pxmeta.user.service.IUserWithdrawService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.HashMap;
import java.util.List;

@RestController
@RequestMapping("/user/bill")
@RequiredArgsConstructor
@Api(value = "用户账单",tags = "用户账单")
@Slf4j
@CrossOrigin
public class UserBillController {

    private final IUserBillService userBillService;
    private final IUserService userService;
    private final IUserWithdrawService userWithdrawService;

    @GetMapping("/getCoinRecords")
    @ApiOperation("获取金币记录")
    public AjaxResult<List<UserBillVO>> getCoinRecord(@RequestParam Integer page,
                                    @RequestParam Integer size){

        Long userId = SecurityUtils.getUserId();
        List<UserBillVO> list = userBillService.getCoinRecords(userId, page, size);
        return AjaxResult.success(list);
    }

    @GetMapping("/getProfitRecords")
    @ApiOperation("获取收益记录")
    public AjaxResult<List<UserBillVO>> getProfitRecords(@RequestParam Integer page,
                                       @RequestParam Integer size){
        Long userId = SecurityUtils.getUserId();
        List<UserBillVO> list = userBillService.getProfitRecords(userId, page, size);
        return AjaxResult.success(list);
    }

    @GetMapping("/getMonthProfit")
    @ApiOperation("获取当月流水")
    public AjaxResult getMonthProfit(){
        Long userId = SecurityUtils.getUserId();
        Double monthProfit = userBillService.getMonthProfit(userId);
        HashMap<String, Double> map = Maps.newHashMap();
        map.put("monthProfit",monthProfit);
        return AjaxResult.success(map);
    }


    @GetMapping("/getTotalProfit")
    @ApiOperation("获取总收益")
    public AjaxResult getTotalProfit(){
        Long userId = SecurityUtils.getUserId();
        User user = userService.getById(userId);
        BigDecimal totalProfit = user.getTotalProfit();

        HashMap<String, Object> map = Maps.newHashMap();
        map.put("totalProfit", totalProfit);
        return AjaxResult.success(map);
    }


    @ApiOperation("获取上次提现记录")
    @GetMapping("/getLastWithdrawRecord")
    public AjaxResult getLastWithdrawRecord(){
        Long userId = SecurityUtils.getUserId();
        UserWithdraw userWithdraw = userWithdrawService.getLastWithdrawRecord(userId);
        return AjaxResult.success(userWithdraw);
    }


    @ApiOperation("申请提现")
    @PostMapping("/applyWithdraw")
    public AjaxResult applyWithdraw(@RequestBody ApplyWithdrawDTO dto){
        Long userId = SecurityUtils.getUserId();
        userBillService.appWithdraw(userId, dto);
        return AjaxResult.success();
    }

    @SaCheckLogin
    @ApiOperation("转增金币")
    @GetMapping("/giveBalance")
    public AjaxResult giveBalance(@RequestParam Integer number,
                                  @RequestParam String account){

        Long userId = SecurityUtils.getUserId();
        User user = userService.getById(userId);
        if (user == null){
            return AjaxResult.error("用户不存在！");
        }

        Integer isGiveBalance = user.getIsGiveBalance();
        if (isGiveBalance == null || isGiveBalance !=1){
            return AjaxResult.error("未开通该权限！");
        }
        BigDecimal balance = user.getBalance();
        balance =  balance.subtract(BigDecimal.valueOf(number));
        if (balance.doubleValue()<0){
            return AjaxResult.error("数量有误！");
        }
        user.setBalance(balance);
        userService.updateById(user);

        User targetUser = userService.getByAccount(account);
        BigDecimal targetBalance = targetUser.getBalance();
        targetBalance = targetBalance.add(BigDecimal.valueOf(number));
        targetUser.setBalance(targetBalance);
        userService.updateById(targetUser);

        //记录支出
        UserBill userBill = new UserBill();
        userBill.setStatus(Status.SUCCESS.getValue());
        userBill.setUserId(userId);
        userBill.setTargetId(targetUser.getId());
        userBill.setPm(0);
        userBill.setCategory(UserBillCategoryEnum.BALANCE.getCategory());
        userBill.setType(UserBillTypeEnum.SYSTEM.getType());
        userBill.setNumber(BigDecimal.valueOf(number));
        userBill.setDescription(String.format("送给用户%s「%s」转赠金币成功！",targetUser.getAccount(),targetUser.getNickname()));
        userBillService.save(userBill);

        //记录收益
        UserBill targetUserBill = new UserBill();
        targetUserBill.setStatus(Status.SUCCESS.getValue()); //状态是否要变为审核中？
        targetUserBill.setUserId(targetUser.getId());
        targetUserBill.setTargetId(userId);
        targetUserBill.setPm(1);
        targetUserBill.setType(UserBillTypeEnum.PARTY_GIFT.getType());
        targetUserBill.setCategory(UserBillCategoryEnum.BALANCE.getCategory());
        targetUserBill.setNumber(BigDecimal.valueOf(number));
        targetUserBill.setDescription(String.format("成功收到用户%s「%s」转赠金币！",user.getAccount(),user.getNickname()));
        userBillService.save(targetUserBill);
        return AjaxResult.success();
    }


    @SaCheckLogin
    @ApiOperation("兑换金币")
    @GetMapping("/exchangeBalance")
    public AjaxResult exchangeBalance(@RequestParam Integer number){
//        return AjaxResult.error("功能维护中！");
        double total =  BigDecimal.valueOf((double)number/100).setScale(2, RoundingMode.HALF_UP).doubleValue();
        Long userId = SecurityUtils.getUserId();
        User user = userService.getById(userId);
        BigDecimal balance = user.getBalance();
        BigDecimal totalProfit = user.getTotalProfit();
        totalProfit = totalProfit.subtract(BigDecimal.valueOf(total));
        BigDecimal finalBalance = balance.add(BigDecimal.valueOf(number));
        user.setBalance(finalBalance);
        if (totalProfit.doubleValue()<0){
            return AjaxResult.error("数量有误！");
        }
        user.setTotalProfit(totalProfit);
        userService.updateById(user);
        return AjaxResult.success();
    }


    @GetMapping("/getWithdrawRecords")
    @ApiOperation("获取提现记录")
    public AjaxResult<List<UserBillVO>> getWithdrawRecords(@RequestParam Integer page,
                                                       @RequestParam Integer size){
        Long userId = SecurityUtils.getUserId();
        List<UserBillVO> list = userBillService.getWithdrawRecords(userId, page, size);
        return AjaxResult.success(list);
    }

}
